import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import sys
import os
import argparse
import os

names_standard = {
    "AliStorage2019":"AliStorage",
    "FbHdp_distribution":"FacebookHdp",
    "WebSearch_distribution":"WebSearch",
    "GoogleRPC2008":"GoogleRPC"
}

def calculate_cdf_bytes(flow_sizes):
    # 对流大小排序
    sorted_sizes = sorted(flow_sizes)
    n = sum(sorted_sizes)
    
    # 计算CDF
    # 对于第 i 个流(size)的CDF = (i+1)/n * 100%
    cdf_data = [[],[]]
    cum_size = 0
    for i, size in enumerate(sorted_sizes):
        cum_size += size
        cdf_val = cum_size / n * 100
        cdf_data[0].append(size )
        cdf_data[1].append(cdf_val)
    return cdf_data



# matplotlib.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei']  # 替换成你安装的中文字体名称
# matplotlib.rcParams['axes.unicode_minus'] = False

def plot_cdf_flows(filenames, save_name=None):
    plt.figure(figsize=(12, 8))
    plt.tick_params(labelsize=40)
    
    for filename in filenames:
        filename = os.path.join("../input", filename)
        if not os.path.isfile(filename):
            print(f"警告: 文件 {filename} 不存在，跳过。")
            continue
        try:
            # 读取数据，假设以空白字符分隔，无表头
            data = pd.read_csv(filename, sep='\s+', header=None)
            if data.shape[1] < 2:
                print(f"警告: 文件 {filename} 数据格式不正确，跳过。")
                continue
            flow_size = data.iloc[:, 0]
            cdf_prob = data.iloc[:, 1]
            # 使用文件名（不含扩展名）作为标签
            label = names_standard[os.path.splitext(os.path.basename(filename))[0]]
            print(label)
            plt.plot(flow_size, cdf_prob, label=label, linewidth=4)
        except Exception as e:
            print(f"错误: 读取文件 {filename} 时出错: {e}")
    
    # 配置图像属性
    plt.xlabel('Flow Size(Byte)', fontsize=40)
    plt.ylabel('CDF(%)', fontsize=40)
    plt.legend(prop={'size': 28, 'weight': 'normal'},columnspacing=1)
    plt.grid(True, which="both", ls="--", linewidth=0.5)
    plt.xscale('log')
    
    plt.ylim(0, 100)
    plt.tight_layout()
    
    # 保存图像
    png_save_name = f'{save_name}.png'
    plt.savefig(png_save_name, format='png', dpi=300, bbox_inches="tight")
    pdf_save_name = f'{save_name}.pdf'
    plt.savefig(pdf_save_name, format='pdf', dpi=300, bbox_inches="tight")
    print(f"图像已保存到{png_save_name}.png {pdf_save_name}.pdf")


def plot_cdf_bytes(files, save_name):
    plt.figure(figsize=(12, 8))
    plt.tick_params(labelsize=40)
    
    for file in files:
        file_name = os.path.splitext(os.path.basename(file))[0]
        os.system(f'python3 dc_traffic_gen.py -c {file_name}.txt -n 32 -l 0.3 -b 10G -t 2 -o {file_name}_tmp.txt --cp 0')

        data = pd.read_csv(f"../output/{file_name}_tmp.txt", sep='\s+', header=None, skiprows=1)
        flows_size = list(data.iloc[:10000, 4])
        
        # 计算cdf纵坐标值
        cdf_bytes_results = calculate_cdf_bytes(flows_size)
        plt.plot(cdf_bytes_results[0], cdf_bytes_results[1], label=names_standard[file_name], linewidth=4)
        
        os.system(f'rm ../output/{file_name}_tmp.txt')
    
    plt.xlabel('Flow Size(Byte)', fontsize=40)
    plt.ylabel('CDF(%)', fontsize=40)
    plt.legend(prop={'size': 28, 'weight': 'normal'},columnspacing=1)
    plt.grid(True, which="both", ls="--", linewidth=0.5)
    plt.xscale('log')
    
    plt.ylim(0, 100)
    plt.tight_layout()
    
    png_save_name = f'{save_name}.png'
    plt.savefig(png_save_name, format='png', dpi=300, bbox_inches="tight")
    pdf_save_name = f'{save_name}.pdf'
    plt.savefig(pdf_save_name, format='pdf', dpi=300, bbox_inches="tight")
    print(f"图像已保存到{png_save_name}.png {pdf_save_name}.pdf")
        
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("用法: python3 plot_cdf.py file1.txt file2.txt")
        sys.exit(1)
    
    parser = argparse.ArgumentParser(description='绘制多个流大小CDF曲线。')
    parser.add_argument('files', metavar='F', type=str, nargs='+',
                        help='包含流大小和CDF概率的文件')
    
    args = parser.parse_args()
    files = args.files
    
    plot_cdf_flows(files, save_name="cdf_flows")
    plot_cdf_bytes(files, save_name="cdf_bytes")
